package czk.concrent.threadpool.hungry;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 饥饿现象的解决
 * 不同状态用不同的线程池
 * @Author:ChenZhangKun
 * @Date: 2020/7/5 20:47
 */
@SuppressWarnings("all")
public class ThreadHungrySolution {
    // 准备四种菜
    private static List<String> order= Arrays.asList("红烧肉","小煎鸭","宫保鸡丁","东坡肘子","藿香鲫鱼");
    // 随机点菜
    private static String food(){
        return order.get(new Random().nextInt(order.size()));
    }

    public static void main(String[] args) {
        //
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        ExecutorService cookPool = Executors.newFixedThreadPool(1);
        // 开启一个线程哇
        executorService.submit(()->{
            System.out.println("处理点菜");
            // 新开线程做菜
            Future<?> cooking = cookPool.submit(() -> {
                System.out.print("做菜  ");
                return food();
            });
            try {
                String o = (String) cooking.get();
                System.out.println(o);
            } catch (InterruptedException | ExecutionException ex) {
                ex.printStackTrace();
            }
        });
        // 再开一个线程，不同状态的线程在不同的线程池中，所以不会有饥饿状态
        executorService.submit(()->{
            System.out.println("处理点菜");
            // 新开线程做菜
            Future<?> cooking = cookPool.submit(() -> {
                System.out.print("做菜  ");
                return food();
            });
            try {
                String o = (String) cooking.get();
                System.out.println(o);
            } catch (InterruptedException |ExecutionException ex) {
                ex.printStackTrace();
            }
        });
    }
}
